<?php
  /**
   *  Recebe um Zend_Db_Table_Select e cria um Zend_Form_Element_Select
   */
class Arm_Form_Element_SelectFromDbSelect extends Zend_Form_Element_Select
{
    ### Model da entidade referenciada
    private $_model             = '';
    
    ### Coluna chave-primária da tabela
    ### ID por default, mas pode ser setada.
    private $_identityColumn    = 'id';
    
    ## Coluna a ser exibida no select
    private $_valueColumn       = null;
    
    ### Para fazer condicional "where"
    private $_select            = null;
    
    public function init(){
        parent::init();
    }
    
    public function setModel($model){
        $this->_model           = $model;
    }
    
    public function setIdentityColumn($identityColumn){
        $this->_identityColumn  = $identityColumn;
    }
    
    public function setValueColumn($valueColumn){
        $this->_valueColumn     = $valueColumn;
    }
    
    public function setSelect($select){
        $this->_select          = $select;
    }
    
    public function render(Zend_View_Interface $view  = null){
        $this->_performSelect();
        return parent::render($view);
    }
    
    ## Realiza a consulta de acordo com os valores setados (ou os valores default)
    ## e a partir do resultado, constroi o select
    private function _performSelect(){
        $model          = new $this->_model;
        $results        = $model->fetchAll($this->_select);
        
        $options[null]  = "";
        foreach($results as $item){
            $array  = $item->toArray();
            if(!is_null($this->_valueColumn)){
                $options[$array[$this->_identityColumn]]    = $array[$this->_valueColumn];
            }
            else{
                $options[$array[$this->_identityColumn]]    = $item->__toString();
            }
        }
        
        $this->setMultiOptions($options);
    }
}
